<template>
    <form action="/">
        <van-search
            v-model="searchText"
            show-action
            placeholder="请输入要搜索的标签"
            @search="onSearch"
            @cancel="onCancel"
            @clear="onClear"
        />
    </form>
    <van-divider content-position="left">已选标签</van-divider>
    <div v-if="activeIds.length == 0">请选择标签</div>
    <van-row :gutter="16">
        <van-col v-for="tag in activeIds" :key="tag.id">
            <van-tag closeable size="medium" type="primary" @close="doClose(tag)" style="margin-bottom: 10px">
                {{ tag }}
            </van-tag>
        </van-col>
    </van-row>

    <van-divider content-position="left">选择标签</van-divider>
    <van-tree-select v-model:active-id="activeIds" v-model:main-active-index="activeIndex" :items="tagList" />
    <div style="padding: 12px">
        <van-button block type="primary" @click="doSearchResult">搜索</van-button>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import router from '../router'

const searchText = ref('')

const originTagList = [
    {
        text: '性别',
        children: [
            { text: '男', id: '男' },
            { text: '女', id: '女' }
        ]
    },
    {
        text: '年级',
        children: [
            { text: '大一', id: '大一' },
            { text: '大二', id: '大二' },
            { text: '大3', id: '大3' },
            { text: '大4', id: '大4' },
            { text: '大5', id: '大5' },
            { text: '大6', id: '大6' }
        ]
    }
]

const onSearch = () => {
    tagList.value = originTagList.map(parentTag => {
        return {
            ...parentTag,
            children: parentTag.children.filter(item => item.text.includes(searchText.value))
        }
    })
}

const onClear = () => {
    tagList.value = originTagList
}

const onCancel = () => {
    router.back();
}

// 已选中的标签
const activeIds = ref([])
const activeIndex = ref(0)

// 标签列表
const tagList = ref([
    {
        text: '性别',
        children: [
            { text: '男', id: '男' },
            { text: '女', id: '女' }
        ]
    },
    {
        text: '年级',
        children: [
            { text: '大一', id: '大一' },
            { text: '大二', id: '大二' },
            { text: '大3', id: '大3' },
            { text: '大4', id: '大4' },
            { text: '大5', id: '大5' },
            { text: '大6', id: '大6' }
        ]
    }
])

// 移除标签
const doClose = (tag: any) => {
    activeIds.value = activeIds.value.filter(item => item !== tag)
}

/**
 * 执行搜索
 */
const doSearchResult = () => {
    router.push({
        path: '/user/list',
        query: {
            tags: activeIds.value
        }
    })
}
</script>

<style scoped></style>